/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.codec.text;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.common.IoSession;

import com.cqcis.uip.base.framework.codec.ObjectEncoder;
import com.cqcis.uip.base.framework.common.HttpParam;
import com.cqcis.uip.base.framework.service.StreamLogOutputService;
import com.cqcis.uip.base.framework.utils.ByteBuffer;
import com.cqcis.uip.base.framework.utils.StringUtil;

/**
 * HTTP 编码
 * 
 * @author huangmy
 * @date   2008-12-4
 */
public class HttpProtocolEncoder implements ObjectEncoder {
	private static Log log = LogFactory.getLog(HttpProtocolEncoder.class);

	/**
	 * 转换为buffer
	 */
	public ByteBuffer encode(Object message) throws Exception {
		HttpParam p = (HttpParam)message;		
		
		StreamLogOutputService streamService = (StreamLogOutputService)p.getAttribute(HttpParam.STREAM_LOG_OUT_SERVICE);
		if (streamService != null) {
			IoSession session = p.getSession();
			HttpParam recvP = (HttpParam)session.getAttribute(HttpParam.CONSTRAIN_KEY_RECV);
			if (recvP != null && !StringUtil.hasText(recvP.getRecordId())) {				
				ByteBuffer sendBuffer = p.buf() != null ? p
						.buf() : ByteBuffer.allocate(4).flip();				
				ByteBuffer recvBuffer = recvP.buf() != null ? recvP
						.buf() : ByteBuffer.allocate(4).flip();
				
				try {
					streamService.write(p.getRecordId(), sendBuffer, recvBuffer);
				} catch (Exception e) {
					log.error("Catch Exception in Write stream log.", e);
				}
			}
		}
		
		return p.buf();
	}
}
